package com.example.dialog.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.dialog.R;
import com.example.dialog.Tools.DatabaseHelperForSearchHistory;
import com.example.dialog.Tools.DatabaseHelperForSearchResult;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {
    private ImageView iv_back;
    private EditText et_search_text;
    private Button btn_search;
    private ListView lv_search_results;
    private TextView tv_search_history;
    private ImageView iv_clear_search;
    private ListView lv_search_history;
    private View v_separator;
    private View tv_search_recommend;
    private ListView lv_search_recommend;
    private LinearLayout lo_search_fragment1;
    private LinearLayout lo_search_fragment2;

    private List<String> searchResults;//搜索结果列表
    private ArrayAdapter<String> adapter;//适配器


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        this.iv_back = findViewById(R.id.iv_back); //返回导航
        this.et_search_text = findViewById(R.id.et_search_text); //搜索输入框
        this.btn_search = findViewById(R.id.btn_search); //搜索按钮
        this.lv_search_results = findViewById(R.id.lv_search_results); //搜索匹配结果
        this.tv_search_history = findViewById(R.id.tv_search_history); //历史记录标题
        this.iv_clear_search = findViewById(R.id.iv_clear_search); //清除历史记录按钮
        this.lv_search_history = findViewById(R.id.lv_search_history); //搜索历史记录
        this.v_separator = findViewById(R.id.v_separator); //分割线
        this.lv_search_recommend = findViewById(R.id.lv_search_recommend); //热点搜索
        this.lo_search_fragment1 = findViewById(R.id.lo_search_fragment1);  //子布局1
        this.lo_search_fragment2 = findViewById(R.id.lo_search_fragment2);  //子布局2

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回首页
                Intent intent=new Intent(SearchActivity.this, HomeActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_from_right);
                finish();
            }
        });

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = et_search_text.getText().toString();
                if (!text.isEmpty()) {
                    new DatabaseHelperForSearchHistory(getApplicationContext()).saveSearchHistory(text);
                    refreshList(); // 刷新列表显示最新的搜索历史

                    lv_search_results.setVisibility(View.GONE);

                    //调用搜索详情界面
                    Intent intent=new Intent(SearchActivity.this, SearchResultsActivity.class);
                    intent.putExtra("et_search_text", text); // 添加额外的数据
                    startActivity(intent);
                    overridePendingTransition(0, 0);//取消切换动画
                }
            }
        });

        iv_clear_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清除数据库中的搜索历史
                showClearSearchHistoryDialog();
                // 刷新ListView以显示更新
                refreshList();
            }
        });
        refreshList(); // 初始化时加载搜索历史

        // 创建一个包含固定热搜数据的 ArrayList
        List<String> hotSearches = new ArrayList<>();
        hotSearches.add("家人们谁懂啊");
        hotSearches.add("震惊，万里某下头男……");
        hotSearches.add("自己吓自己是什么梗");
        hotSearches.add("以色列遭数千枚火箭弹袭击");
        hotSearches.add("孩子在《英雄联盟》里国服排名第 9 名，我能做什么？");

        // 创建一个 ArrayAdapter，并将 ArrayList 设置为数据源
        ArrayAdapter<String> hotSearches_adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, // 指定列表项的布局
                hotSearches); // 数据源

        // 搜索建议
        lv_search_recommend.setAdapter(hotSearches_adapter);

        // 初始化搜索结果列表和适配器
        this.searchResults = new ArrayList<>();
        this.adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, searchResults);
        this.lv_search_results.setAdapter(adapter);

        this.lv_search_results.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取Adapter中的数据
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) lv_search_results.getAdapter();
                String selectedItemText = adapter.getItem(position);

                // 设置EditText的文本为点击的项的文本
                et_search_text.setText(selectedItemText);
                et_search_text.setSelection(et_search_text.getText().length()); //设置光标到末尾
                btn_search.callOnClick();   //调用搜索按钮事件
            }
        });
        this.lv_search_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取Adapter中的数据
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) lv_search_history.getAdapter();
                String selectedItemText = adapter.getItem(position);

                // 设置EditText的文本为点击的项的文本
                et_search_text.setText(selectedItemText);
                et_search_text.setSelection(et_search_text.getText().length()); //设置光标到末尾
                btn_search.callOnClick();   //调用搜索按钮事件
            }
        });
        this.lv_search_recommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取Adapter中的数据
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) lv_search_recommend.getAdapter();
                String selectedItemText = adapter.getItem(position);

                // 设置EditText的文本为点击的项的文本
                et_search_text.setText(selectedItemText);
                et_search_text.setSelection(et_search_text.getText().length()); //设置光标到末尾
                btn_search.callOnClick();   //调用搜索按钮事件
            }
        });
    }//onCreate函数


    private void revealHistoryBar(){    //显示历史记录栏
        tv_search_history.setVisibility(View.VISIBLE);
        iv_clear_search.setVisibility(View.VISIBLE);
        v_separator.setVisibility(View.VISIBLE);
    }
    private void hideHistoryBar(){  //隐藏历史记录栏
        tv_search_history.setVisibility(View.GONE);
        iv_clear_search.setVisibility(View.GONE);
        v_separator.setVisibility(View.GONE);
    }
    public void refreshList() {
        List<String> searchHistory = new DatabaseHelperForSearchHistory(this).getAllSearchHistory();
        if(!searchHistory.isEmpty()){
            revealHistoryBar(); //有记录，设置相关控件可见
        }
        else{
            hideHistoryBar(); //设置相关控件不可见
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, searchHistory);
        lv_search_history.setAdapter(adapter);
    }
    private void showClearSearchHistoryDialog() {
        new AlertDialog.Builder(this)
                .setTitle("清除搜索历史")
                .setMessage("确定要清除所有搜索历史吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击确定，清除搜索历史
                        new DatabaseHelperForSearchHistory(getApplicationContext()).clearSearchHistory();
                        hideHistoryBar();
                        refreshList(); // 刷新ListView以显示更新后的结果
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击取消，不执行任何操作
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }


    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (!charSequence.toString().isEmpty()) {
                // EditText 不为空，显示搜索结果列表，隐藏<!-- 历史搜索/搜索发现 -->
                lv_search_results.setVisibility(View.VISIBLE);
                lo_search_fragment2.setVisibility(View.GONE);
            } else {
                // EditText 为空，隐藏搜索结果列表，显示<!-- 历史搜索/搜索发现 -->
                lv_search_results.setVisibility(View.GONE);
                lo_search_fragment2.setVisibility(View.VISIBLE);

            }
            search(charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    public void search(String query) {
        // 清空搜索结果列表
        searchResults.clear();
        // 执行搜索逻辑，这里假设是从数据库或其他数据源搜索
        // 例如，你可以在这里执行一个异步任务来获取搜索结果

        // 假设找到了匹配项
        List<String> searchHistory = new DatabaseHelperForSearchResult(this).querySearchDataBase(query);
        searchResults.addAll(searchHistory);

        // 更新适配器和ListView
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        et_search_text.addTextChangedListener(textWatcher);
    }
}